package com.wutianyi.favority.recommend;

import java.util.TimerTask;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;

import com.wutianyi.favority.FavorityRepository;
import com.wutianyi.favority.rel.RelTypes;

public class LinkedRecommendTimer extends TimerTask {

	private FavorityRepository favority;

	public LinkedRecommendTimer(FavorityRepository favority) {
		this.favority = favority;
	}

	@Override
	public void run() {

		Node linkRoot = favority.getLinkRoot();
		Iterable<Relationship> rs = linkRoot.getRelationships(RelTypes.LINK,
				Direction.OUTGOING);
		Transaction tx = favority.getGraphDb().beginTx();
		try {
			int count = 0;
			for (Relationship r : rs) {
				Node linkNode = r.getEndNode();
				if (linkNode.hasProperty("update")) {
					Iterable<Relationship> lrs = linkNode.getRelationships(
							RelTypes.LINKED, Direction.INCOMING);
					count++;
					int linkCount = 0;
					for (Relationship lr : lrs) {
						linkCount++;
					}
					linkNode.removeProperty("update");
					linkNode.setProperty("count", linkCount);
				}
				if (count >= 10000) {
					tx.success();
					tx.finish();
					tx = favority.getGraphDb().beginTx();
				}
			}
		} finally {
			tx.success();
			tx.finish();
		}

	}

}
